package com.msi.shortwave;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.osmdroid.bonuspack.location.GeocoderNominatim;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.msi.shortwave.home.doupdate;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Time;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView.RecyclerListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class results extends ListFragment {
	ProgressDialog loading;
	Dialog dialog;
	String logtext = "";
	public static final String PREFS_NAME = "swprefs";
	String timetext = "";
	AudioRecord mRecorder;
	final List<frequency> listOfFreqs = new ArrayList<frequency>();
	 View v;
	 ArrayList<ArrayList> trans = new ArrayList<ArrayList>();
	 ArrayList<Bundle> all = new ArrayList<Bundle>();
	 String disttext = "";
	 public static final int NUM_CHANNELS = 1;
		public static final int SAMPLE_RATE = 8000;
		public static final int BITRATE = 32;
		public static final int MODE = 1;
		public static final int QUALITY = 2;
		MediaPlayer mediaPlayer ;
		private short[] mBuffer;
		private File mRawFile;
		private File mEncodedFile;
		private boolean mIsRecording = false;
		private boolean mIsPlaying = false;
		
	 public String padStr(String val) {
		  while (val.length() < 4)
			  val = "0" + val;
		  return val;
		}
	 
		private void mLockScreenRotation()
		{
		  // Stop the screen orientation changing during an event
		    switch (this.getResources().getConfiguration().orientation)
		    {
		  case Configuration.ORIENTATION_PORTRAIT:
		    getActivity().setRequestedOrientation(
		ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		    break;
		  case Configuration.ORIENTATION_LANDSCAPE:
			  getActivity().setRequestedOrientation(
		ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		    break;
		    }
		}

	 public boolean isOnline() {
			
			if (AppStatus.getInstance(getActivity()).isOnline((getActivity()))){
				return true;
			}else{
				//blackberry below
				//return true;
				//android below
				return false;
			}
		}
	 
	 public void stoprecord(){
		 

    	 
    	 if (mIsRecording){
    		
    	 mIsRecording = false;

    	 mRecorder.stop();
    	 
    	 mRecorder.release();
    	 Mp3tools  convert2mp3= new Mp3tools();
    	

			int result = convert2mp3.convertfile(mRawFile, mEncodedFile);
	    	 
	    	 

     }
    	 if (mIsPlaying){
  mediaPlayer.stop();
  mediaPlayer.reset();

  mediaPlayer.release();
	

    	 }
    	 
	 }
	 
 	
	 ListView list;
	 
	
	 LayoutInflater passinflate;
    
     private ArrayList<frequency> m_orders = null;
     private frequencyadaptor m_adapter;
     long type;
     
	  String targetlat;
	  String targetlong;
    
/*
	   public void onListItemClick(ListView l, View v, int position, long id) {
			// TODO Auto-generated method stub
			super.onListItemClick(l, v, position, id);
			Fragment mFragmentR;
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			 
			 int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
			// Log.i("SW4",String.valueOf(status));
			 
      	
		    
	    	
	    		 Bundle bund1 =  new Bundle();
	   bund1.putSerializable("markers",trans.get(position));
	   bund1.putBoolean("all",false);
	   
	   if (isOnline()==true){
   		   bund1.putBoolean("offline",false);
   		   if(status == ConnectionResult.SUCCESS) {
      	       //Success! Do what you want
      	  
 			    	mFragmentR=new maps ();
      	   }else{
 			    	mFragmentR=new mapsosm ();

      	   }
   			   
   		   }else{
	    		   bund1.putBoolean("offline",true);
	    		   mFragmentR=new mapsosm ();
   		   }
	
	    	//	   bund1.putSerializable("markers",all);

		
		mFragmentR.setArguments(bund1);
		
		
		  if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {     
		        ft.replace(R.id.fragment_content2, mFragmentR, null);
		    }else if((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {     

		        ft.replace(R.id.fragment_content2, mFragmentR, null);
		    }else{
	    	ft.replace(R.id.fragment_content, mFragmentR, null);
		    }
		ft.addToBackStack(null);

		ft.commit();
		    
		    }
	   
	   
	   
	  
           */
	  
	  private void startBufferedWrite(final File file) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					File swdir = new File(Environment.getExternalStorageDirectory().toString() + "/shortwave/");
			        if (!swdir.exists()) {
			        	swdir.mkdirs();}
					DataOutputStream output = null;
					try {
						output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
						while (mIsRecording) {
							int readSize = mRecorder.read(mBuffer, 0, mBuffer.length);
							for (int i = 0; i < readSize; i++) {
								output.writeShort(mBuffer[i]);
							}
						}
					} catch (IOException e) {
						Log.i("SW4","A" + e.toString());
					} finally {
						if (output != null) {
							try {
								output.flush();
							} catch (IOException e) {
								Log.i("SW4","B" + e.toString());

							} finally {
								try {
									output.close();
								} catch (IOException e) {
									Log.i("SW4","C" + e.toString());

								}
							}
						}
					}
				}
			}).start();
		}

	  
	  private File getFile(String freq,final String suffix) {
			Time time = new Time();
			time.setToNow();
			return new File(Environment.getExternalStorageDirectory() + "/shortwave/", freq+"-"+time.format("%Y%m%d%H%M%S") + "." + suffix);
		}
	  
	  void Sharer(String shareBody, String strdbdate, String rxloc, String stationname, String freq, String transname, String logdatetime, String language, String country, String power, String azi, String lat, String longitude, String logtext, String target, String filename, String sig, String shorturl, Boolean share ){
		  SimpleDateFormat dateFormatGmt = new SimpleDateFormat("HHmm d MMM ");
	        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); 
		  addlogdb(stationname, freq, transname, 
		    		strdbdate, language, country, rxloc,power, azi, lat,longitude, shareBody, target, filename, sig, shorturl);
		  if (share){
		  Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND); 
		    sharingIntent.setType("text/plain");
		    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, stationname+ " " + dateFormatGmt.format(new Date()));
		    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
		   

		startActivity(Intent.createChooser(sharingIntent, "Share via"));
		  }
			dialog.dismiss();
	  }


	   @Override
	   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	      // Inflate the layout for this fragment
	     v = inflater.inflate(R.layout.results, container, false);
	    
	      Bundle bund1 = getArguments();
	      passinflate = inflater;
	      listOfFreqs.clear();
	      
	      String time = bund1.getString("time");
			String target = bund1.getString("target");
			String language = bund1.getString("language");
			String station = bund1.getString("station");
			String freq = bund1.getString("freq");
	        m_orders = new ArrayList<frequency>();
	        
			new searchdb().execute(time,target,station,freq,language);
			
			
		
			 final Button button = (Button) v.findViewById(R.id.buttonmap);
		       button.setOnClickListener(new View.OnClickListener() {
		           public void onClick(View v) {
		        	   
		        	   FragmentTransaction ft = getFragmentManager().beginTransaction();

		        	   Fragment mFragmentR;
		        	   int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
		        	   if(status == ConnectionResult.SUCCESS) {
		        	       //Success! Do what you want
		   			    	mFragmentR=new maps ();
		        	   }else{
		   			    	mFragmentR=new mapsosm ();

		        	   }
		   		 
		   	    	
		   	    		 Bundle bund1 =  new Bundle();
		   	   // bund1.putSerializable("markers",trans.get(position));
		   	    		   bund1.putSerializable("markers",all);
		   	    		   Log.i("SW4",all.toString());

		   	    		   bund1.putBoolean("all",true);
			        	   if (isOnline()==true){
			   	    		   bund1.putBoolean("offline",false);
	   
			   	    		 if(status == ConnectionResult.SUCCESS) {
				        	       //Success! Do what you want
				   			    	mFragmentR=new maps ();
				        	   }else{
				   			    	mFragmentR=new mapsosm ();

				        	   }
			   	    		   
			   	    		   }else{
				   	    		   bund1.putBoolean("offline",true);
				   			    	mFragmentR=new mapsosm ();

			   	    		   }


		   	    		
		   		mFragmentR.setArguments(bund1);
		   		
		   	
		   		  if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {     
		   		        ft.replace(R.id.fragment_content2, mFragmentR, null);
		   		    }else if((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {     

		   		        ft.replace(R.id.fragment_content2, mFragmentR, null);
		   		    }else{
		   	    	ft.replace(R.id.fragment_content, mFragmentR, null);
		   		    }
		   		ft.addToBackStack(null);
		   	
		   		ft.commit();   
		        	   
		          
		           
		        
		           }
		       });
		      
		      return v;
		 
	   }
	   
	   String siglevel (){
			String sigstring = "";
		   RatingBar signal = (RatingBar) dialog.findViewById(R.id.sigrat);
		   RatingBar interference = (RatingBar) dialog.findViewById(R.id.sigint);
		   RatingBar noise = (RatingBar) dialog.findViewById(R.id.signoise);
		   RatingBar prop = (RatingBar) dialog.findViewById(R.id.sigprop);
		   RatingBar overall = (RatingBar) dialog.findViewById(R.id.sigoverall);
		   Log.i("SW4", "SIG = " +String.valueOf(signal.getRating()));
		  
		   if (signal.getRating()  > 0 && interference.getRating()  > 0 && noise.getRating()  > 0 && prop.getRating() > 0 &&  overall.getRating()  > 0){
			   sigstring = " SINPO = "+ String.valueOf(Math.round(signal.getRating()))+ String.valueOf(Math.round(interference.getRating()))+ String.valueOf(Math.round(noise.getRating()))+ String.valueOf(Math.round(prop.getRating()))+ String.valueOf(Math.round(overall.getRating()))+". ";
			   Log.i("SW4", "SIG1 = " +String.valueOf(signal.getRating()));
		   }else  if (signal.getRating()  > 0 && interference.getRating()  > 0 && overall.getRating()  > 0){

			   sigstring = " SIO = "+ String.valueOf(Math.round(signal.getRating()))+ String.valueOf(Math.round(interference.getRating()))+ String.valueOf(Math.round(overall.getRating()))+". ";
			   Log.i("SW4", "SIG2 = " +String.valueOf(signal.getRating()));
		   }
		  
		
		return sigstring;
		   
	   }
	   
	   public String updatetext(ArrayList<Bundle> clickedtrans,int pos, String timetext){
   		final SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);

			if (!settings.getString("locationname", "").equals("")){
	 			   EditText dialogloc = (EditText) dialog.findViewById(R.id.yourlocation);
	 			  dialogloc.setText(settings.getString("locationname", ""));
	 			  
	 			 if (!settings.getString("latitude", "").equals("")){
	 			  
	 			 Location locationA = new Location("Your loc");

	 			 
	 			 
	 			locationA.setLatitude(Double.valueOf(settings.getString("latitude", "")));
	 			locationA.setLongitude(Double.valueOf(settings.getString("longitude", "")));

	 			Location locationB = new Location("point B");
	 			   Spinner freqspin = (Spinner) dialog.findViewById(R.id.freqspinner);
	 			   
	 			  freqspin.getSelectedItemPosition();
	 			 String getlong = (String) clickedtrans.get(pos).get("long");
	 			 String getlat = (String) clickedtrans.get(pos).get("lat");
	 			 
	 			 
	 			 
	 			if (getlong.contains("W")){
	 				getlong=getlong.replace("W", ".");
	 				getlong = "-" + getlong;
	 			}else{
	 				getlong = getlong.replace("E", ".");
	 			}
	 			
	 			if (getlat.contains("S")){
	 				getlat = getlat.replace("S", ".");
	 				getlat = "-" + getlat;
	 			}else{
	 				getlat = getlat.replace("N", ".");
	 			}
	 			
	 			if (!getlat.equals("")){
	 			 
	 			locationB.setLatitude(Double.valueOf(getlat));

	 			locationB.setLongitude(Double.valueOf(getlong));


	 			float distance = locationA.distanceTo(locationB);
	 			 if (!clickedtrans.get(pos).get("name").equals("")){
	 			 
	 				 disttext = " Received at " + settings.getString("locationname", "") +", " +  String.valueOf(Math.round(distance/1000))+"KM from transmitter at " +  clickedtrans.get(pos).get("name") + ". "+ timetext;
	 			 }else{
	 				disttext = " Distance from TX to RX is " + String.valueOf(distance/1000)+"KM. " + timetext;

	 			 }
	 			}else{
	 				 disttext = " Received at " + settings.getString("locationname", "")+". " + timetext;

	 			}
	 		   }
	 		   }
			  SimpleDateFormat dateFormatGmt = new SimpleDateFormat("HHmm d MMM ");
		        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
		       
		        
		        
		   String logtext = (String) clickedtrans.get(pos).get("freq") + " " + dateFormatGmt.format(new Date()).toUpperCase()+ "- "+ 
		        ((String) clickedtrans.get(pos).get("stationname")).toUpperCase();
		   
		   if (!clickedtrans.get(pos).get("country").equals("")){
			   logtext = logtext + " (" + ((String) clickedtrans.get(pos).get("country")).toUpperCase() + ") ";
		   }
		   
		   
		   if (!clickedtrans.get(pos).get("language").equals("")){
			   logtext = logtext + " in " + ((String) clickedtrans.get(pos).get("language")).toUpperCase();
		   }
		   	
		   if (!clickedtrans.get(pos).get("name").equals("")){
			   logtext = logtext + " from " + ((String) clickedtrans.get(pos).get("name")).toUpperCase();
		   }
		   logtext = logtext + ".";
		   
		return logtext;
		   
	   }
	   
	   public  void logclick(int position){
		
		// custom dialog
		   dialog = new Dialog(getActivity());
					dialog.setContentView(R.layout.dialog_log);
					disttext = "";
					mEncodedFile = null;
					SimpleDateFormat dbformat = new SimpleDateFormat(
				                "yyyy-MM-dd HH:mm:ss");
					
					dbformat.setTimeZone(TimeZone.getTimeZone("GMT"));
					final Date dbdate = new Date();
					final String strdbdate = dbformat.format(dbdate);
					
					
					dialog.setTitle("Add to Log");
					final Time today = new Time(Time.getCurrentTimezone());
					today.setToNow();
					
					timetext = "Local time: " + String.valueOf(today.hour)+String.valueOf(today.minute)+".";
					final EditText comment = (EditText)dialog.findViewById(R.id.comment);
					final EditText locationedit = (EditText)dialog.findViewById(R.id.yourlocation);
					locationedit.addTextChangedListener(new TextWatcher(){
				        public void afterTextChanged(Editable s) {
				        	disttext = " Recieved at " + locationedit.getText().toString() + ". " + timetext;
				        }
				    	@Override
				        public void beforeTextChanged(CharSequence s, int start, int count, int after){}
				    	@Override
				        public void onTextChanged(CharSequence s, int start, int before, int count){}
					
					
				    }); 
					
					final Spinner s = (Spinner) dialog.findViewById(R.id.freqspinner);
					ArrayAdapter<String> adapterForSpinner = new ArrayAdapter<String>(getActivity(),
			        		android.R.layout.simple_spinner_item);
			  		                adapterForSpinner.setDropDownViewResource
			  		(android.R.layout.simple_spinner_dropdown_item);
			  		            
					// set the custom dialog components - text, image and button
					final ArrayList<Bundle> clickedtrans = trans.get(position);
					Log.i("SW4",clickedtrans.toString());
					//Log.i("SW4",clickedtrans.toString());
					for(Bundle transitem : clickedtrans){
						adapterForSpinner.add(transitem.getString("stationname") + " " + transitem.getString("freq")+" ("+transitem.getString("name") + ")");

					}
					 s.setAdapter(adapterForSpinner); 				
					 
					 s.setOnItemSelectedListener(new OnItemSelectedListener() {
						    @Override
						    public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
						        // your code here
						    	logtext = updatetext(clickedtrans,s.getSelectedItemPosition(),timetext);
						    
						    	
						    	
						    }

						    @Override
						    public void onNothingSelected(AdapterView<?> parentView) {
						        // your code here
						    }

						});
					 
					 Button dialogButton = (Button) dialog.findViewById(R.id.button_ok);
					// if button is clicked, close the custom dialog
					dialogButton.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							stoprecord();
							   String commentext = comment.getText().toString();
							    if (commentext.length() > 0){
							    	commentext = commentext + ".";
							    }
							  String shareBody =  logtext + siglevel() +  commentext + disttext;
							    String sig = siglevel();
							    
							    final SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
							    String rxloc =  settings.getString("locationname", "");

							    String filename = "";
							    if (mEncodedFile!=null){
							    	filename = mEncodedFile.getAbsolutePath();
							    	Bundle mp3data = new Bundle();
						    		mp3data.putString("frequrl", clickedtrans.get(s.getSelectedItemPosition()).getString("freq").trim().replace(".", "-").replace("Khz", ""));
						    		mp3data.putString("filename", filename);
						    		mp3data.putString("sharebody", shareBody);
						    		mp3data.putString("strdbdate", strdbdate);
						    		mp3data.putString("rxloc", rxloc);
						    		mp3data.putString("stationname", clickedtrans.get(s.getSelectedItemPosition()).getString("stationname"));

						    		mp3data.putString("freq", clickedtrans.get(s.getSelectedItemPosition()).getString("freq"));

						    		mp3data.putString("name", clickedtrans.get(s.getSelectedItemPosition()).getString("name"));
						    		mp3data.putString("language", clickedtrans.get(s.getSelectedItemPosition()).getString("language"));
						    		mp3data.putString("country", clickedtrans.get(s.getSelectedItemPosition()).getString("country"));
						    		mp3data.putString("power", clickedtrans.get(s.getSelectedItemPosition()).getString("power"));
						    		mp3data.putString("azi", clickedtrans.get(s.getSelectedItemPosition()).getString("azi"));
						    		mp3data.putString("lat", clickedtrans.get(s.getSelectedItemPosition()).getString("lat"));
						    		mp3data.putString("long", clickedtrans.get(s.getSelectedItemPosition()).getString("long"));
						    		mp3data.putString("targets", clickedtrans.get(s.getSelectedItemPosition()).getString("targets"));
						    		mp3data.putBoolean("share",false);
						    		mp3data.putString("sig", sig);

									
									new uploadmp3().execute(mp3data);
									
									  dialog.dismiss();   
							    }else{
							    
							    addlogdb(clickedtrans.get(s.getSelectedItemPosition()).getString("stationname"), clickedtrans.get(s.getSelectedItemPosition()).getString("freq"), clickedtrans.get(s.getSelectedItemPosition()).getString("name"), 
							    		strdbdate, clickedtrans.get(s.getSelectedItemPosition()).getString("language"), clickedtrans.get(s.getSelectedItemPosition()).getString("country"), rxloc, clickedtrans.get(s.getSelectedItemPosition()).getString("power"), clickedtrans.get(s.getSelectedItemPosition()).getString("azi"), clickedtrans.get(s.getSelectedItemPosition()).getString("lat"), clickedtrans.get(s.getSelectedItemPosition()).getString("long"), shareBody, clickedtrans.get(s.getSelectedItemPosition()).getString("targets"), filename, sig,"");


							    dialog.dismiss();   
							    }
							    
						}
					});
					
					 Button shareButton = (Button) dialog.findViewById(R.id.button_share);
						// if button is clicked, close the custom dialog
					 shareButton.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								
								stoprecord();
								
							    SimpleDateFormat dateFormatGmt = new SimpleDateFormat("HHmm d MMM");
						        dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));

						        
							    String commentext = comment.getText().toString();
							    if (commentext.length() > 0){
							    	commentext = commentext + ".";
							    }
							    String shareBody =  logtext + siglevel() +  commentext + disttext;
							    String sig = siglevel();
							    
							    final SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
							    
							    String filename = "";
								 
							    	String rxloc =  settings.getString("locationname", "");

							    if (mEncodedFile!=null){
							    	filename = mEncodedFile.getAbsolutePath();
							    	
							    	
							    		Bundle mp3data = new Bundle();
							    		mp3data.putString("frequrl", clickedtrans.get(s.getSelectedItemPosition()).getString("freq").trim().replace(".", "-").replace("Khz", ""));
							    		mp3data.putString("filename", filename);
							    		mp3data.putString("sharebody", shareBody);
							    		mp3data.putString("strdbdate", strdbdate);
							    		mp3data.putString("rxloc", rxloc);
							    		mp3data.putString("stationname", clickedtrans.get(s.getSelectedItemPosition()).getString("stationname"));

							    		mp3data.putString("freq", clickedtrans.get(s.getSelectedItemPosition()).getString("freq"));

							    		mp3data.putString("name", clickedtrans.get(s.getSelectedItemPosition()).getString("name"));
							    		mp3data.putString("language", clickedtrans.get(s.getSelectedItemPosition()).getString("language"));
							    		mp3data.putString("country", clickedtrans.get(s.getSelectedItemPosition()).getString("country"));
							    		mp3data.putString("power", clickedtrans.get(s.getSelectedItemPosition()).getString("power"));
							    		mp3data.putString("azi", clickedtrans.get(s.getSelectedItemPosition()).getString("azi"));
							    		mp3data.putString("lat", clickedtrans.get(s.getSelectedItemPosition()).getString("lat"));
							    		mp3data.putString("long", clickedtrans.get(s.getSelectedItemPosition()).getString("long"));
							    		mp3data.putString("targets", clickedtrans.get(s.getSelectedItemPosition()).getString("targets"));
							    		mp3data.putString("sig", sig);
							    		mp3data.putBoolean("share",true);


										
										new uploadmp3().execute(mp3data);
							    
									
							    	
							    	
							    }else{
							    	Sharer(shareBody, strdbdate, rxloc, clickedtrans.get(s.getSelectedItemPosition()).getString("stationname"), clickedtrans.get(s.getSelectedItemPosition()).getString("freq"), clickedtrans.get(s.getSelectedItemPosition()).getString("name"), 
							    			strdbdate, clickedtrans.get(s.getSelectedItemPosition()).getString("language"), clickedtrans.get(s.getSelectedItemPosition()).getString("country"), clickedtrans.get(s.getSelectedItemPosition()).getString("power"), clickedtrans.get(s.getSelectedItemPosition()).getString("azi"), clickedtrans.get(s.getSelectedItemPosition()).getString("lat"), clickedtrans.get(s.getSelectedItemPosition()).getString("long"), shareBody, clickedtrans.get(s.getSelectedItemPosition()).getString("targets"), filename, sig, "", true);
							    }
							    
							  
							}
						});
					 final TextView status = (TextView) dialog.findViewById(R.id.lblstatus);
					 final ImageView imgStop = (ImageView) dialog.findViewById(R.id.ImageStop);
					 final ImageView imgRec = (ImageView) dialog.findViewById(R.id.ImageRec);
					 final ImageView imgPlay = (ImageView) dialog.findViewById(R.id.ImagePlay);

					 imgRec.setOnClickListener(new View.OnClickListener() {
					     @Override
					     public void onClick(View v) {
					    	 Log.i("SW4","REC");
					    	int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
					 				AudioFormat.ENCODING_PCM_16BIT);
					 		mBuffer = new short[bufferSize];
					 		mRecorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
					 				AudioFormat.ENCODING_PCM_16BIT, bufferSize);
					 	
					 		imgRec.setVisibility(View.INVISIBLE);
					 		imgStop.setVisibility(View.VISIBLE);

					 		mIsRecording = true;

					    	 mRecorder.startRecording();
					    	 status.setText("Recording...");
								mRawFile = getFile(clickedtrans.get(s.getSelectedItemPosition()).getString("freq"),"raw");
								mEncodedFile= getFile(clickedtrans.get(s.getSelectedItemPosition()).getString("freq"),"mp3");

								startBufferedWrite(mRawFile);

					     }
					 });
					 
					 imgPlay.setOnClickListener(new View.OnClickListener() {
					     @Override
					     public void onClick(View v) {
					    	 imgRec.setVisibility(View.INVISIBLE);
						 		imgStop.setVisibility(View.VISIBLE);
		   			    		 imgPlay.setVisibility(View.INVISIBLE);

					    	    FileDescriptor fd = null;
					    	    String audioPath = mEncodedFile.getAbsolutePath();
					            FileInputStream fis = null;
								try {
									fis = new FileInputStream(audioPath);
								} catch (FileNotFoundException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
					            try {
									fd = fis.getFD();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
					            
					          
					                 mediaPlayer = new MediaPlayer();
					                 
					                 mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
					                     @Override
					                     public void onCompletion(MediaPlayer mp) {
					                         // TODO Auto-generated method stub
					                    	 mediaPlayer.stop();
					   					  mediaPlayer.reset();
					   			    		 imgRec.setVisibility(View.VISIBLE);
					   			    		 imgPlay.setVisibility(View.VISIBLE);
					   			    		 imgStop.setVisibility(View.INVISIBLE);
					   			    		 mIsPlaying = false;

					   					  mediaPlayer.release();
					   				    	 status.setText("");
					                     }


					                 });
					                 
					                try {
										mediaPlayer.setDataSource(fd);
									} catch (IllegalArgumentException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IllegalStateException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
					                try {
										mediaPlayer.prepare();
									} catch (IllegalStateException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
							    	 status.setText("Playing...");

					                mIsPlaying = true;
					                mediaPlayer.start();
					                
					       

					     }
					 });
					 
					 
	
					 
	 imgStop.setOnClickListener(new View.OnClickListener() {
					     @Override
					     public void onClick(View v) {
					    	 
					    	 if (mIsRecording){
					    		 imgRec.setVisibility(View.VISIBLE);
					    		 imgStop.setVisibility(View.INVISIBLE);
					    		 imgPlay.setVisibility(View.VISIBLE);

					    	 mIsRecording = false;

					    	 mRecorder.stop();
					    	 
					    	 mRecorder.release();
					    	 Mp3tools  convert2mp3= new Mp3tools();
					    	 status.setText("Encoding...");

								int result = convert2mp3.convertfile(mRawFile, mEncodedFile);
						    	 status.setText("Complete");
						    	 

					     }
					    	 if (mIsPlaying){
					  mediaPlayer.stop();
					  mediaPlayer.reset();
			    		 imgRec.setVisibility(View.VISIBLE);
			    		 imgPlay.setVisibility(View.VISIBLE);
			    		 imgStop.setVisibility(View.VISIBLE);

					  mediaPlayer.release();
				    	 status.setText("");


					    	 }
					    	 
					     }
					 });
					 
	 
					 
					 Button cancelButton = (Button) dialog.findViewById(R.id.button_cancel);
						// if button is clicked, close the custom dialog
					 cancelButton.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
					
							dialog.dismiss();
							}
						});
					 
					 Button updateloc = (Button) dialog.findViewById(R.id.buttongetloc);
						// if button is clicked, close the custom dialog
					 updateloc.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								 new getloc().execute(clickedtrans);
							}
						});
					 
					
					 
					 
					dialog.show();
					
		   
	   }
	   
	   
	   public void addlogdb(String stationname, String freq, String transname, String logdatetime, String language, String country, String rxloc, String power, String azi, String lat, String longitude, String logtext, String target, String filename, String sig, String url){
		   SQLiteDatabase fDB= null;
			SQLiteStatement insert;
			Log.i("SW4","Lang" + language);
			fDB = getActivity().openOrCreateDatabase("shortwave", getActivity().MODE_PRIVATE, null);
			fDB.beginTransaction();

			 String sqllog = "INSERT INTO logs (stationname, freq, transname, logdatetime, language, country, rxloc, power, azi, lat, long, logtext, target, filename,sig, url)  VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
		       	insert = fDB.compileStatement(sqllog);
		       	insert.bindString(1,stationname);insert.bindString(2,freq);insert.bindString(3,transname);insert.bindString(4,logdatetime);insert.bindString(5,language);
		       	insert.bindString(6,country);insert.bindString(7,rxloc);insert.bindString(8,power);insert.bindString(9,azi);insert.bindString(10,lat);
		       	insert.bindString(11,longitude);insert.bindString(12,logtext);insert.bindString(13,target);insert.bindString(14,filename);insert.bindString(15,sig);insert.bindString(16,url);
		       	insert.executeInsert();
		       	fDB.setTransactionSuccessful();
		       	fDB.endTransaction();
		       	fDB.close();
	   }
	   
	 
	   public void mapclick(int position){
		   
		   Fragment mFragmentR;
			FragmentTransaction ft = getFragmentManager().beginTransaction();
			 
			 int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
			// Log.i("SW4",String.valueOf(status));
			 
     	
		    
	    	
	    		 Bundle bund1 =  new Bundle();
	   bund1.putSerializable("markers",trans.get(position));
	   bund1.putBoolean("all",false);
	   
	   if (isOnline()==true){
  		   bund1.putBoolean("offline",false);
  		   if(status == ConnectionResult.SUCCESS) {
     	       //Success! Do what you want
     	  
			    	mFragmentR=new maps ();
     	   }else{
			    	mFragmentR=new mapsosm ();

     	   }
  			   
  		   }else{
	    		   bund1.putBoolean("offline",true);
	    		   mFragmentR=new mapsosm ();
  		   }
	
	    	//	   bund1.putSerializable("markers",all);

		
		mFragmentR.setArguments(bund1);
		
		
		  if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {     
		        ft.replace(R.id.fragment_content2, mFragmentR, null);
		    }else if((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {     

		        ft.replace(R.id.fragment_content2, mFragmentR, null);
		    }else{
	    	ft.replace(R.id.fragment_content, mFragmentR, null);
		    }
		ft.addToBackStack(null);

		ft.commit();
		   
		   
	   }
	   
	   public class uploadmp3 extends AsyncTask<Bundle, Void, Bundle> {

		@Override
		protected void onPostExecute(Bundle result) {
			// TODO Auto-generated method stub
			loading.dismiss();
			
			String shareBody = result.getString("sharebody") + " Audio: " + result.getString("shorturl");

			Sharer(shareBody, result.getString("strdbdate"), result.getString("rxloc"), result.getString("stationname"), result.getString("freq"), result.getString("name"),  result.getString("strdbdate"),
					result.getString("language"),  result.getString("country"), result.getString("power"), result.getString("azi"), result.getString("lat"), result.getString("long"), shareBody, result.getString("targets"), result.getString("filename"), result.getString("sig"),result.getString("shorturl"),result.getBoolean("share"));
			
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
		}

		@Override
		protected Bundle doInBackground(Bundle... params) {
			// TODO Auto-generated method stub
			 String shorturl = "";
			 Bundle mp3data = new Bundle();
			 mp3data = params[0];
			String khz = mp3data.getString("frequrl");
			String filename =  mp3data.getString("filename");
			String url = "http://"+khz+".khz.mobi/addsound.php";
			
			 if (isOnline()){
			HttpClient httpClient = new DefaultHttpClient();
		    HttpContext localContext = new BasicHttpContext();
		    HttpPost httpPost = new HttpPost(url);

		    try {
		        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

		                entity.addPart("file", new FileBody(new File (filename)));
	
		        httpPost.setEntity(entity);

		        HttpResponse response = httpClient.execute(httpPost, localContext);
		        shorturl = EntityUtils.toString(response.getEntity());
		    } catch (IOException e) {
		        e.printStackTrace();
		        shorturl = "";
		    }
			 }
		    mp3data.putString("shorturl", shorturl);
			return mp3data;
		    
			
		}
		
		@Override
    	protected void onPreExecute() {
    		 mLockScreenRotation();
	    	 loading = ProgressDialog.show(getActivity(),"Please wait..", "Uploading MP3", true);
    	}
    	
    
		   
	   }
	   
	   
	   public class getloc extends AsyncTask<ArrayList<Bundle>, Void, ArrayList<Bundle>> {

		@Override
		protected ArrayList<Bundle> doInBackground(ArrayList<Bundle>... arg0) {
			
	        ArrayList<Bundle> passed = arg0[0];
			
		    LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
		    Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			if (isOnline() && location!=null){
				
				List<Address> locationname = null;
				 int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
	        	   if(status == ConnectionResult.SUCCESS) {
	        	       //Success! Play services location
	        		   Geocoder geocoder = new Geocoder(getActivity());
	              		try {
							//locationname = geocoder.getFromLocation(53.6454, -3.0083, 1);

			 				locationname = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

			 			    } catch (IOException e) {
			 			        e.printStackTrace();
			 		        	
			 			    }
	        		  
	        	   }else{
	   			    	
	        	       //Failure! Use OSM
	        		   
	        			GeocoderNominatim geocoder = new GeocoderNominatim(getActivity());
	               		try {
			 				locationname = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

							//locationname = geocoder.getFromLocation(53.6454, -3.0083, 1);
							


			 			    } catch (IOException e) {
			 			        e.printStackTrace();
			 		        	
			 			    }
			 			}

	 
	       		String locality = "";
	       		String subloc = "";
 				String country = "";
 				String strlocation = "";
 			        if (locationname.size() > 0) {
 			        	Log.i("SW4",locationname.toString());
 			        	subloc = String.valueOf(locationname.get(0).getSubLocality());
 			        	locality = String.valueOf(locationname.get(0).getLocality());
 			        	country = String.valueOf(locationname.get(0).getCountryName());

 			        	if (locality==null || locality.equals("null") ){
 			        		strlocation = country;
 			        	}else {
 			        		strlocation = locality +", " + country;
 			        	}
 			        	Log.i("SW4",strlocation);


 			        	SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME,0);
 					      SharedPreferences.Editor editor = settings.edit();
 					      editor.putString("locationname", strlocation);
 					    editor.putString("latitude", String.valueOf(location.getLatitude()));
 					   editor.putString("longitude", String.valueOf(location.getLongitude()));
 					 //editor.putString("latitude", "53.6");
					 //  editor.putString("longitude", "-3");
 					      editor.commit();
 			        	
 			        }
	        	  
 			        
				
			}else{
				
			}
			return passed;
		}
		
	    	@Override
	    	protected void onPreExecute() {
	    		 mLockScreenRotation();
	    	 loading = ProgressDialog.show(getActivity(),"Please wait..", "Getting location", true);
	    	}
	    	
	    	@Override 
	    	protected void onPostExecute(ArrayList<Bundle> bundle) {
	    		
	    		
	    		final SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
	    		
	    		
	 		   if (!settings.getString("locationname", "").equals("")){
	 			   EditText dialogloc = (EditText) dialog.findViewById(R.id.yourlocation);
	 			  dialogloc.setText(settings.getString("locationname", ""));
	 			  
	 			 if (!settings.getString("latitude", "").equals("")){
	 			  
	 			 Location locationA = new Location("Your loc");

	 			 
	 			 
	 			locationA.setLatitude(Double.valueOf(settings.getString("latitude", "")));
	 			locationA.setLongitude(Double.valueOf(settings.getString("longitude", "")));

	 			Location locationB = new Location("point B");
	 			   Spinner freqspin = (Spinner) dialog.findViewById(R.id.freqspinner);
	 			   
	 			 int pos = freqspin.getSelectedItemPosition();
	 			 String getlong = (String) bundle.get(pos).get("long");
	 			 String getlat = (String) bundle.get(pos).get("lat");

	 			if (getlong.contains("W")){
	 				getlong=getlong.replace("W", ".");
	 				getlong = "-" + getlong;
	 			}else{
	 				getlong = getlong.replace("E", ".");
	 			}
	 			
	 			if (getlat.contains("S")){
	 				getlat = getlat.replace("S", ".");
	 				getlat = "-" + getlat;
	 			}else{
	 				getlat = getlat.replace("N", ".");
	 			}
	 			 
	 			locationB.setLatitude(Double.valueOf(getlat));

	 			locationB.setLongitude(Double.valueOf(getlong));


	 			float distance = locationA.distanceTo(locationB);
	 			
		 	
	 			
	 			 if (!bundle.get(pos).get("name").equals("")){
	 			 
	 				 
	 				 disttext = " Received at " + settings.getString("locationname", "") +", " +  String.valueOf(Math.round(distance/1000))+"KM from transmitter at " +  bundle.get(pos).get("name") + ". "  + timetext;
	 			 }else{
	 				disttext = " Distance from TX to RX is " + String.valueOf(distance/1000)+"KM. " + timetext;

	 			 }
	 		   }
	 		   }
	    		 loading.dismiss();
	    		getActivity().setRequestedOrientation(
	    				ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
	    	
	    	}

		   
		
		   
	   }
	   
	   private class searchdb extends AsyncTask<String, Void, String> {
	    	ProgressDialog loading;
	    	@Override
	    	
	    	
	    	protected String doInBackground(String... params) {
	       
	            
	    		String time = params[0].toString();
	    		String target = params[1].toString();
	    		String station = params[2].toString();
	    		String freq = params[3].toString();
	    		String language = params[4].toString();
	    		String timesql = "";
	    		String stationsql = "";
	    		String targetsql = "";
	    		String freqsql = "";
	    		String sqlquery = "";
	    		String langsql = "";
	    		
	    		//Log.i("SW", language);
	    		
	    		if (language.equals("999") == false && language.equals("0") == false ){
	    			 langsql = "language = '" + language + "' AND" ;
	    			
	    			
	    		}
	    	     
	    	    

	    	     if (time.equals("nullnull") == false && time.equals("null") == false && time.equals("") == false){
	    	    	 //timesql = "'" + time + "' BETWEEN timestart AND timeend AND ";
	    	    	 timesql = "CASE WHEN (timeend < timestart) THEN 1+24 ELSE '" + time + "' BETWEEN timestart AND timeend END AND ";

	    		     sqlquery = "SELECT stations.id, stations.name, schedule.timestart, schedule.timeend, schedule.id, stations.country, schedule.target, schedule.language FROM schedule, stations  WHERE " + timesql + stationsql + langsql+ " stations.id = schedule.station ORDER BY stations.name ASC";

	    	     }
	    	     
	    	     if (station != null && station.equals("") == false){
	    	    	 stationsql = "stations.id = '" + station + "' AND ";
	    		     sqlquery = "SELECT stations.id, stations.name, schedule.timestart, schedule.timeend, schedule.id, stations.country, schedule.target, schedule.language FROM schedule, stations  WHERE " + timesql + stationsql + langsql + " stations.id = schedule.station ORDER BY schedule.timestart ASC";

	    	     }
	    	     
	    	     if (target.equals("999") == false && target.equals("null") == false && target.equals("") == false){
	    		     sqlquery = "SELECT stations.id, stations.name, schedule.timestart, schedule.timeend, schedule.id, stations.country, schedule.target , schedule.language FROM stations, schedule WHERE  "+ timesql + langsql + "  target = '" + target + "' AND stations.id = schedule.station ORDER by stations.name ASC";
	    		  
	    	     }
	    	     
	    	     if (freq.equals("") == false && freq != null){
	    		     sqlquery = "SELECT stations.id, stations.name, schedule.timestart, schedule.timeend, schedule.id, stations.country, schedule.target, schedule.language,  schedule.timeend + 2400 AS timeend24 FROM stations, schedule WHERE  "+ timesql + langsql + " schedule.id IN (SELECT schedule FROM frequencyschedule WHERE CAST(frequency AS INTEGER) > '" + (Integer.valueOf(freq)-9) + "' AND CAST(frequency AS INTEGER) < '" + (Integer.valueOf(freq)+9) + "') AND stations.id = schedule.station ORDER by stations.name ASC";
	    	     }
	    	     
	    	     all.clear();
	    	     SQLiteDatabase myDB= null;
	    			myDB = getActivity().openOrCreateDatabase("shortwave", getActivity().MODE_PRIVATE, null);
	    			Cursor c = myDB.rawQuery(sqlquery,null);
	    			if (c.getCount() > 0)
	    			{
	    			    	while(c.moveToNext())
	    			    	{
	    			    		Boolean include = false;
	    			    		 ArrayList<Bundle> itemtrans = new ArrayList<Bundle>();
	    			    		 //if ((time.equals("nullnull") || time.equals("")) || Integer.valueOf(c.getString(2)) <= Integer.valueOf(time) || (Integer.valueOf(c.getString(3)) < Integer.valueOf(c.getString(2)) && Integer.valueOf(c.getString(3)) < Integer.valueOf(time) + 2400 ) ){
	    			    		if ((time.equals("nullnull") || time.equals(""))) {
	    			    			include = true;
	    			    		}else{
	    			    		 if (Integer.valueOf(c.getString(2)) > Integer.valueOf(c.getString(3))){
	    			    			//Log.i("SW4",c.getString(2) + time);
	    			    			//Log.i("SW4",c.getString(3) + time);

	    			    			 if (Integer.valueOf(time) > Integer.valueOf(c.getString(2)) && Integer.valueOf(time) < Integer.valueOf(c.getString(3))+2400){
	    			    				 include = true;
	    			    				 Log.i("SW4",c.getString(2) + " HERE" + c.getString(3));
	    			    			 }
	    			    			 
	    			    			 if (Integer.valueOf(time) > Integer.valueOf(c.getString(2))-2400 && Integer.valueOf(time) < Integer.valueOf(c.getString(3))){
	    			    				 include = true;
	    			    				 Log.i("SW4",c.getString(2) + " HERE NEW" + c.getString(3));
	    			    			 }
	    			    		 }else{
	    			    			 include = true;
	    			    		 }
	    			    		}
	    			    	
	    			    	if (include == true){

	    			    		 Cursor e = myDB.rawQuery("SELECT targets.target,targets.type,targets.lat,targets.long FROM targets WHERE targets.code = '" + c.getString(6) + "'",null);
		    			    		String targets = "";  
		    			    		//Log.i("SW3","SELECT targets.target,targets.type,targets.lat,targets.long FROM targets WHERE targets.code = " + c.getString(6) );
		    						if (e.getCount() > 0){
		    							  while(e.moveToNext()){
		    								 
		    								  targets = e.getString(0);
		    								  type =  e.getLong(1);
		    								  targetlat = e.getString(2);
		    								  targetlong = e.getString(3);
		    							  }
		    						  }
		    							  
		    			    		
		    			    		e.close();
		    			    		
		    			    		Cursor f = myDB.rawQuery("SELECT language FROM languages WHERE languages.code = '" + c.getString(7) + "'",null);
		    			    		String langfromdb = "";  

		    						if (f.getCount() > 0){
		    							  while(f.moveToNext()){
		    								  langfromdb = f.getString(0);
		    							  }
		    						  }
		    							  
		    			    		
		    			    		f.close();
	    			    		 
	    						Cursor d = myDB.rawQuery("SELECT frequencyschedule.frequency, transmitters.transmitter, transmitters.latitude, transmitters.longitude,frequencyschedule.azi, frequencyschedule.power FROM frequencyschedule LEFT JOIN transmitters ON frequencyschedule.transmitter= transmitters.id WHERE frequencyschedule.schedule = '" + c.getString(4) + "'",null);
	    						String freqs = "";  
	    						if (d.getCount() > 0){
	    							  while(d.moveToNext()){
	    								  if (d.getString(1) == null){
	    									  freqs = freqs + d.getString(0) + " ";
	    									  Bundle item = new Bundle();
	    									  item.putString("name", "");
	    									  item.putString("lat", "");
	    									  item.putString("long", "");
	    									  item.putLong("type", type);
	    									  item.putString("targetlat", targetlat);
	    									  item.putString("targetlong", targetlong);
	    									  item.putString("azi", d.getString(4));
	    									  item.putString("power", d.getString(5));
	    									  item.putString("targets", targets);
	    									  item.putString("freq", d.getString(0)+"Khz");
	    									  item.putString("stationname", c.getString(1));
	    									  item.putString("language",langfromdb);
	    									  item.putString("country", c.getString(5));
	    									  itemtrans.add(item);

	    								  }else{
	    									 
	    									  freqs = freqs + d.getString(0) + " ("+ d.getString(1) + ") ";
	    									  Bundle item = new Bundle();
	    									  item.putString("name", d.getString(1));
	    									  item.putString("lat", d.getString(2));
	    									  item.putString("long", d.getString(3));
	    									  item.putLong("type", type);
	    									  item.putString("targetlat", targetlat);
	    									  item.putString("targetlong", targetlong);
	    									  item.putString("azi", d.getString(4));
	    									  item.putString("power", d.getString(5));
	    									  item.putString("targets", targets);
	    									  item.putString("freq", d.getString(0)+"Khz");
	    									  item.putString("stationname", c.getString(1));
	    									  item.putString("language",langfromdb);
	    									  item.putString("country", c.getString(5));
	    									  itemtrans.add(item);
	    									  
	    									  if ( d.getString(2).length() > 0 & d.getString(4).length() > 0){
	    									  all.add(item);
	    									  }
	    								  }
	    							  }
	    						  }
	    						trans.add(itemtrans);
	    							  
	    			    		
	    			    		d.close();
	    			    		

	    			    		
	    							  
	    			    		
	    			    		e.close();
	    			    		
	    			
	    			    		String title = "";
	    			    		if (language.compareTo("") == 0){
	    			    			title = c.getString(1) + " (" + c.getString(5) +")";
	    			    		}else{
	    			    			title =c.getString(1) + " (" + c.getString(5) +") " + getString(R.string.languagein) + " " + langfromdb;
	    			    		}
	    		
	    			    	
	    			    		
	    			    		
	    			    		listOfFreqs.add(new frequency(title,  padStr(c.getString(2)),  padStr(c.getString(3)), targets ,freqs));
	    			    	}
	    			    	}
	    			    }
	    			    c.close();
	    			    myDB.close();
	    			    
	    	  

	    	       
	    	  
	    	            
	    		return null;
	    	}

	    	/* (non-Javadoc)
	    	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	    	 */
	    	@Override
	    	protected void onPostExecute(String result) {
	   		 //list = (ListView) v.findViewById(R.id.ListView01);
	    	//	   list.setClickable(true);
	    	//	   Log.i("SW",String.valueOf(adapter.getCount()));
	    	//	 list.setAdapter(adapter);
	    	//	   list.setOnItemClickListener(new OnItemClickListener() {
	    			   	
	   	      //      @Override
	   	            //public void onItemClick(AdapterView<?> arg0, View view, int position, long index) {
	   	      //          
	   	              //on click show menu
	   	     //       }
	   	     //   });
	    		
	    		for(int k=0;k<listOfFreqs.size();k++){
	    			frequency freqlistitem = listOfFreqs.get(k);
	    			
	    			frequency freqitem = new frequency(freqlistitem.getStationname(),freqlistitem.getStarttime(),freqlistitem.getEndtime(),freqlistitem.getTargets(),freqlistitem.getFreqs());
	    			
		              m_orders.add(freqitem);
	    		}
	    		 
	    		
	              
	    	
	    		
	    		  m_adapter = new frequencyadaptor(getActivity(), R.layout.row, m_orders,results.this);
	              setListAdapter(m_adapter);
	    		Log.i("SW",String.valueOf(m_orders.size()));
	    		// m_adapter.add(m_orders.get(0));
	    		//if(m_orders != null && m_orders.size() > 0){
                //  for(int k=0;k<m_orders.size();k++){
                	  
                //  m_adapter.add(m_orders.get(k));
                //  }
                 // }
                  
	    		
             /*
	    		ArrayList test = trans.get(0);
	    		ArrayList test2 = (ArrayList) test.get(0);
	    		Bundle test3 = (Bundle) test2.get(0);
	    		
	    		Log.i("SW3",test3.get("name").toString());
	    		
	    		*/
	    		//Log.i("SW3",trans.toString());
	    		loading.dismiss();
	    		
	  		
	    	}

	    	/* (non-Javadoc)
	    	 * @see android.os.AsyncTask#onPreExecute()
	    	 */
	    	@Override
	    	protected void onPreExecute() {
	    	// Things to be done before execution of long running operation. For example showing ProgessDialog
	    	
	    	 loading = ProgressDialog.show(getActivity(),getString(R.string.pleasewait), getString(R.string.searchingdb), true);
	    	}

	    	/* (non-Javadoc)
	    	 * @see android.os.AsyncTask#onProgressUpdate(Progress[])
	    	 */
	    	@Override
	    	protected void onProgressUpdate(Void... values) {
	          // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
	    	 }
	   }


	
	   

	        
	}